﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web;
using viBook.Common;
using viBook.Controllers;

namespace viBook.Helpers
{
    public static class FileUploadHelper
    {
        public static void SaveFile(this BaseController controller, HttpPostedFileBase file, string path, string thumbnailPath = null)
        {
            var dirPath = String.Format("{0}{1}", controller.Server.MapPath("~"), Constant.SaveImagePath);
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            file.SaveAs(path);

            if (!String.IsNullOrEmpty(thumbnailPath))
            {
                Image thumbnail = Image.FromFile(path);
                Resize(thumbnail, 10).Save(thumbnailPath);
            }
        }

        public static string FileNameFormatter(this BaseController controller, string filename, string prefix = null, string surfix = null)
        {
            return String.Format("{0}{1}\\{2}{3}{4}", controller.Server.MapPath("~"), Constant.SaveImagePath, prefix, filename, surfix);
        }

        private static Image Resize(Image img, int percentage)
        {
            var originalW = img.Width;
            var originalH = img.Height;
            var resizedW = (originalW / percentage);
            var resizedH = (originalH / percentage);

            var bmp = new Bitmap(resizedW, resizedH);
            Graphics graphic = Graphics.FromImage(bmp);
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.DrawImage(img, 0, 0, resizedW, resizedH);
            graphic.Dispose();
            return bmp;
        }

        internal static void SaveFileDictioary(IEnumerable<KeyValuePair<string, HttpPostedFileBase>> dictionary, string dirPath)
        {
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);

            foreach (KeyValuePair<string, HttpPostedFileBase> file in dictionary)
            {
                file.Value.SaveAs(file.Key);
            }
        }
    }
}